﻿using B.S.InOut.Domain;
using B.S.InOut.Read.API.Application.Command;
using B.S.InOutErrorCode;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using static B.S.InOut.Read.API.Application.Command.DeleteOutManageCommand;

namespace B.S.InOut.Read.API.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class OutManageController : ControllerBase
    {
        private readonly IMediator mediator;
        private readonly ILogger<OutManageController> logger;

        public OutManageController(IMediator mediator, ILogger<OutManageController> logger = null)
        {
            this.mediator = mediator;
            this.logger = logger;
        }

        /// <summary>
        /// elk日志测试接口
        /// </summary>
        /// <param name="a"></param>
        /// <returns></returns>
        [HttpGet]
        public int Logger(int a=0)
        {
            try
            {
                int b = 1;
                if(a==b)
                logger.LogInformation("测试elk日志接口");
                return a;
            }
            catch (Exception ex)
            {
                logger.LogError("调用 测试elk日志接口 时发生了异常"+ex.Message);
                return 0;
                throw ;
            }
        }



        // HTTP POST 请求，用于插入产品
        [HttpPost]
        public async Task<IActionResult> InsertOutManage([FromBody] Outmanagement product)
        {
            // 创建插入产品命令
            var command = new InsertOutMenageCommand(product);
            // 发送命令给中介者并获取插入记录的 ID
            var id = await mediator.Send(command);
            // 返回插入记录的 ID
            return Ok(id);
        }

        // HTTP GET 请求，根据 ID 获取产品
        [HttpGet]
        public async Task<IActionResult> GetOutManageById(int Id)
        {
            // 创建获取产品命令
            var command = new GetOutMenageByIdCommand(Id);
            // 发送命令给中介者并获取产品对象
            var product = await mediator.Send(command);
            if (product == null)
            {
                // 如果产品不存在，返回 404 状态码
                return NotFound();
            }
            // 返回产品信息
            return Ok(product);
        }

        // HTTP GET 请求，获取所有产品
        [HttpGet]
        public async Task<IActionResult> GetAlOutManage()
        {
            // 创建获取所有产品命令
            var command = new GetAllOutMenageCommand();
            // 发送命令给中介者并获取产品集合
            var products = await mediator.Send(command);
            // 返回所有产品信息
            return Ok(products);
        }

        // HTTP PUT 请求，更新产品信息
        [HttpPost]
        public async Task<IActionResult> UpdateOutManage([FromBody] Outmanagement product)
        {
            // 创建更新产品命令
            var command = new UpdateOutMenageCommand(product);
            // 发送命令给中介者并获取受影响的行数
            var rowsAffected = await mediator.Send(command);
            if (rowsAffected == 0)
            {
                // 如果没有记录受影响，返回 404 状态码
                return NotFound();
            }
            // 返回更新成功信息
            return Ok("更新成功");
        }


        // HTTP DELETE 请求，根据 ID 删除产品
        [HttpPost]
        public async Task<IActionResult> DeleteOutManage(int id)
        {
            // 创建删除产品命令
            var command = new DeleteOutMenageCommand(id);
            // 发送命令给中介者并获取受影响的行数
            var rowsAffected = await mediator.Send(command);
            if (rowsAffected == 0)
            {
                // 如果没有记录受影响，返回 404 状态码
                return NotFound();
            }
            // 返回删除成功信息
            return Ok("删除成功");
        }
        /// <summary>
        /// 多条件查询出库信息
        /// </summary>
        /// <param name="outboundnumber"></param>
        /// <param name="outbound"></param>
        /// <param name="outAuditstatus"></param>
        /// <param name="pageindex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetProductsByConditions([FromQuery] string? outboundnumber, [FromQuery] int? outbound, [FromQuery] int? outAuditstatus, [FromQuery] int pageindex = 1, [FromQuery] int pageSize = 10)
        {
            Apipaging<Outmanagement> result = new Apipaging<Outmanagement>();

            var command = new GetOutMenageByConditionsCommand(outboundnumber, outbound, outAuditstatus, pageindex, pageSize);
            var products = await mediator.Send(command);
            result.totalcount = products.Count();
            result.totalpage = (int)Math.Ceiling(result.totalcount * 1.0 / pageSize);
            result.List = products.OrderByDescending(p => p.Id).Skip((pageindex - 1) * pageSize).Take(pageSize).ToList();
            return Ok(new { result });
        }
        /// <summary>
        /// 批量删除产品的 HTTP DELETE 方法
        /// </summary>
        /// <param name="productIds">要删除的产品 ID 列表</param>
        /// <returns>操作结果</returns>
        [HttpPost]
        public async Task<IActionResult> DeleteOutManageALL([FromBody] IEnumerable<int> productIds)
        {
            var command = new DeleteOutManageCommand(productIds);
            var rowsAffected = await mediator.Send(command);

            if (rowsAffected > 0)
            {
                return Ok("成功");
            }
            else
            {
                return NotFound("未找到该数据");
            }
        }
        private readonly string _connectionString;

        /// <summary>
        /// 处理联合查询 Outmanagement 和 ProductModel 表的 HTTP GET 请求
        /// </summary>
        /// <returns>联合查询结果的列表</returns>
        [HttpGet("with-product-model")]
        public async Task<IActionResult> GetOutmanagementWithProductModel([FromQuery] string? outboundnumber, [FromQuery] ApiOutbound? outbound,[FromQuery] ApiStatus? outAuditstatus, [FromQuery] int pageindex = 1, [FromQuery] int pageSize = 10)
        {
            
            var command = new GetOutmanagementWithProductModelCommand(outboundnumber, outbound, outAuditstatus,pageindex, pageSize);
            var outproduct= await mediator.Send(command);

            int totalcount = outproduct.Count();
            int totalpage = (int)Math.Ceiling(totalcount * 1.0 / pageSize);
            var list = outproduct.OrderByDescending(p => p.Id).Skip((pageindex - 1) * pageSize).Take(pageSize).ToList();
     
            return Ok(new { totalcount,totalpage,list});
        }




        // HTTP GET 请求，根据 ID 获取产品
        [HttpGet]
        public async Task<IActionResult> GetProoutIdBy(int id)
        {
            // 创建获取产品命令
            var command = new GetOutmanagementAndProductModelByIdCommand(id);
            // 发送命令给中介者并获取产品对象
            var product = await mediator.Send(command);
            if (product == null)
            {
                // 如果产品不存在，返回 404 状态码
                return NotFound();
            }
            // 返回产品信息
            return Ok(product);
        }
        /// <summary>
        /// 根据出库单编号查询数据
        /// </summary>
        /// <param name="Outboundnumber"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetOutmanageNumBy(string Outboundnumber)
        {
            var command = new GetOutmanagemenByIdCommand(Outboundnumber);
            var product = await mediator.Send(command);
            if (product == null)
            {
                // 如果不存在，返回 404 状态码
                return NotFound();
            }
            return Ok(product);
        }


        #region 导出
        ///// <summary>
        ///// 导出
        ///// </summary>
        ///// <param name="commodityIds"></param>
        ///// <returns></returns>
        //[HttpGet]
        //public async Task<IActionResult> ExportOrderList([FromQuery] List<string> Product_id)
        //{
        //    if (Product_id == null || !Product_id.Any())
        //    {
        //        return BadRequest("请提供商品 ID 列表。");
        //    }

        //    var request = new ExportQuserCommand { Product_id = Product_id };
        //    var result = await ExportQuser(request);

        //    if (result.Data?.Any() != true)
        //        return NotFound("未找到商品数据。");

        //    using IWorkbook book = new XSSFWorkbook();
        //    ISheet sheet = book.CreateSheet("商品列表");
        //    IRow headerRow = sheet.CreateRow(0);

        //    // 设置表头
        //    string[] headers = { "产品编号", "产品名称", "产品规格", "类别", "存储单位", "仓库名称", "库位名称", "库位类型", "库存数量", "库存上限", "库存下限", "操作日期", "入库数量", "出库数量", "产品批次编号", "操作备注" };
        //    for (int i = 0; i < headers.Length; i++)
        //        headerRow.CreateCell(i).SetCellValue(headers[i]);

        //    // 填充数据行
        //    int rowIndex = 1;
        //    foreach (var item in result.Data) // 直接使用 result.Data 集合
        //    {
        //        IRow row = sheet.CreateRow(rowIndex++);
        //        row.CreateCell(0).SetCellValue(item.Product_id ?? "");
        //        row.CreateCell(1).SetCellValue(item.Product_name ?? "");
        //        row.CreateCell(2).SetCellValue(item.Spec ?? "");
        //        row.CreateCell(3).SetCellValue(item.Category ?? "");
        //        row.CreateCell(4).SetCellValue(item.Storage_unit ?? "");
        //        row.CreateCell(5).SetCellValue(item.Warehouse_name ?? "");
        //        row.CreateCell(6).SetCellValue(item.Location_name ?? "");
        //        row.CreateCell(7).SetCellValue(item.Location_type ?? "");
        //        row.CreateCell(8).SetCellValue(item.Stock_quantity ?? 0);
        //        row.CreateCell(9).SetCellValue(item.upper_limit ?? 0);
        //        row.CreateCell(10).SetCellValue(item.lower_limit ?? 0);
        //        row.CreateCell(11).SetCellValue(item.Operation_date.ToString("yyyy-MM-dd HH:mm:ss"));
        //        row.CreateCell(12).SetCellValue(item.In_quantity);
        //        row.CreateCell(13).SetCellValue(item.Out_quantity);
        //        row.CreateCell(14).SetCellValue(item.Batch_no ?? "");
        //        row.CreateCell(15).SetCellValue(item.Remark ?? "");
        //    }

        //    using var ms = new MemoryStream();
        //    book.Write(ms);
        //    byte[] buffer = ms.ToArray();

        //    return File(buffer, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "商品列表.xlsx");
        //}
        #endregion


    }
}
